package com.ztorn.utils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;

public class JSONUtil {

	/**
	 * 对象转换为Json字符串
	 * @param o
	 * @return
	 */
	public static String genJson(Object o) {
		String jsonStr = "";
		if (o != null) {
			ObjectMapper obm = new ObjectMapper();
			try {
				jsonStr = obm.writeValueAsString(o);
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return jsonStr;
		
	}

	/**
	 * json字符串转换为JAVA对象
	 * @param jsonData
	 * @param clazz
	 * @return
	 */
	public static <T> T parseJson(String jsonData, Class<T> clazz) {
		T t = null;
		ObjectMapper obm = new ObjectMapper();
		try {
			t = obm.readValue(jsonData, clazz);
		} catch (JsonParseException e) {
			e.printStackTrace();
		} catch (JsonMappingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return t;
	}
	
}